import React, { useEffect, useState, useRef } from 'react';
import { connect, history } from 'umi';
import { Form, Button, Col, Row, Space, Card, notification, Descriptions, Modal } from 'antd';
import { SearchOutlined } from '@ant-design/icons'
import FormCondition from '@/components/FormCondition';
import { phoneReg } from '@/common/regular';
import RadioShopModel from './components/RadioShopModel';
import { pay_type } from '@/common/contact'
import moment from 'moment';
import uploadOss from '@/utils/aliOssUpload';
import { dateNowYearDisabled, dateNowDisabled } from '@/common/regular';
import './index.less'
const OrderForm = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading } = props
  const { detail = {}, show = false, type = 'insert' } = visible
  const [shopInfo, setShopInfo] = useState([])
  const [idCardRule, setIdCardRule] = useState(false)
  const [disabledCard, setDisabledCard] = useState(false)
  const [form] = Form.useForm();
  const [shopData] = shopInfo
  const { openType, orderSn, orderDesc, goodsMinPrice, goodsInfo = {}
  } = detail
  useEffect(() => {

  }, [])
  useEffect(() => {
    if (show && orderSn) {
      const shop = JSON.parse(orderDesc)
      setShopInfo([{ ...shop, minPrice: goodsMinPrice, ...goodsInfo }])
    }
  }, [show])
  useEffect(() => {
    const { location = {} } = history
    const { query = {} } = location
    const { idCard } = query
    if (show) {

      if (idCard) {
        setDisabledCard(true)
      }
    } else {
      setDisabledCard(false)
    }
  }, [show])

  const fetchRoleEdit = () => {

    let data = shopInfo.reduce((item, val) => {
      const { skuid, id, } = val
      return {
        goodsId: id,
        skuId: skuid
      }
    }, {});
    if (!data.goodsId) {
      return notification.error({
        message: '温馨提示',
        description: `请设置订单商品后提交`,
      });
    } else {
      form.validateFields().then(async (values) => {
        const {
          payTime,
          orderDate,
          certificateImages,
        } = values;
        let img = await uploadOss(certificateImages);
        dispatch({
          type: 'order/fakeEnterOrder',
          payload: {
            ...data,
            ...values,
            payTime: payTime.format('YYYY-MM-DD HH:mm'),
            orderDate: orderDate.format('YYYY-MM-DD'),
            certificateImages: img.toString(),
          },
          callback: () => {
            onClose();
          }
        })
      });
    };
  }

  const searchUserInfo = () => {
    dispatch({
      type: 'order/fetchCheckUserInfo',
      payload: {
        mobile: form.getFieldValue('mobileSearch'),
        organizationId: window.localStorage.getItem('organizationId')
      },
      callback: (e) => {
        const { mobile, username, id,
          idCard
        } = e
        form.setFieldsValue({
          mobile: mobile,
          username: username,
          organizationUserId: id,
          idCard: idCard
        })
        if (idCard) {
          setDisabledCard(true)
        }
      }
    })
  }
  const setPriceValue = () => {
    const data = form.getFieldsValue()
    const { realPayFee = 0, payFee = 0 } = data
    const setField = Number(payFee) - Number(realPayFee)
    if (shopData && shopData.minPrice) {
      const setFieldPrice = Number(shopData.minPrice) - Number(payFee)
      form.setFieldValue('additionalDiscounts', setFieldPrice > 0 ? setFieldPrice : 0)
    }
    form.setFieldValue('remainMoney', setField < 0 ? 0 : Math.abs(setField))
  }
  const formItems = [{
    label: '手机查询',
    name: 'mobileSearch',
    disabled: openType === 'user',
    rules: [{ required: false }],
    addonAfter: <SearchOutlined onClick={() => { searchUserInfo() }}></SearchOutlined>
  }, {
    label: '手机',
    name: 'mobile',
    disabled: true
  },
  {
    label: '姓名',
    name: 'username',
    disabled: true
  },
  {
    label: '用户id',
    name: 'organizationUserId',
    hidden: true
  }]

  const formItems3 = [{
    label: '商品数量',
    name: 'goodsAmount',
    visible: typeof shopData === 'object' && shopData.goodsType === 'offline'
  }]
  const formItems1 = [
    {
      label: '收据编号',
      name: 'receiptNo',
      rules: [{ required: false }],
    },
    {
      label: '收据图片',
      name: 'certificateImages',
      rules: [{ required: false }],
      type: 'upload'
    },
    {
      label: '订单备注',
      rules: [{ required: false }],
      name: 'remark',
    },
  ]
  const formItems2 = [
    {
      label: '应收金额',
      name: 'payFee',
      type: 'number',
      onChange: () => {
        setPriceValue()
      }
    },
    {
      label: '实收金额',
      name: 'realPayFee',
      type: 'number',
      onChange: () => {
        setPriceValue()
      }
    },
    {
      label: '欠费',
      name: 'remainMoney',
      disabled: true,
      rules: [{ required: false }],
    },
    {
      label: '超额优惠',
      name: 'additionalDiscounts',
      rules: [{ required: false }],
      disabled: true
    },
    {
      label: '支付方式',
      name: 'payType',
      type: 'select',
      select: pay_type,
    },
    {
      label: '支付时间',
      name: 'payTime',
      showTime: 'HH:mm',
      type: 'dataPicker',
      format: 'YYYY-MM-DD HH:mm',
      disabledDate: dateNowDisabled,
    },
    {
      label: '开单日期',
      name: 'orderDate',
      type: 'dataPicker',
      format: 'YYYY-MM-DD',
      disabledDate: dateNowYearDisabled,
    }
  ]
  return <Card title='录入订单' extra={<Button type='link' onClick={() => onClose()}>返回列表</Button>}>
    <Row>
      <Col span={18}>
        <div className="OrderForm-manage-part">
          <div className="createLive-part-title">
            <div className="createLive-title-line"></div>
            <div className="createLive-part-title-word">用户信息</div>
          </div>
        </div>
        <FormCondition
          form={form}
          formItems={formItems}
          initialValues={detail}
        ></FormCondition>
        <div className="OrderForm-manage-part">
          <div className="createLive-part-title">
            <div className="createLive-title-line"></div>
            <div className="createLive-part-title-word">选择商品</div>
          </div>
        </div>
        <RadioShopModel defail={detail} onChange={(e) => {
          setShopInfo(e)
          form.setFieldsValue({
            payFee: '',
            realPayFee: '',
            remainMoney: '',
            additionalDiscounts: ''
          })
        }} list={shopInfo}></RadioShopModel>
        <FormCondition
          form={form}
          formItems={formItems3}
          initialValues={detail}
        ></FormCondition>
        <div className="OrderForm-manage-part">
          <div className="createLive-part-title">
            <div className="createLive-title-line"></div>
            <div className="createLive-part-title-word">销售信息</div>
          </div>
        </div>
        <FormCondition
          form={form}
          formItems={formItems1}
          initialValues={detail}
        ></FormCondition>
        <div className="OrderForm-manage-part">
          <div className="createLive-part-title">
            <div className="createLive-title-line"></div>
            <div className="createLive-part-title-word">支付信息</div>
          </div>
        </div>
        <FormCondition
          form={form}
          formItems={formItems2}
          initialValues={detail}
        ></FormCondition>
      </Col>
    </Row>
    <Button className='OrderForm_btn' loading={loading} onClick={() => fetchRoleEdit()} type='primary'>保存</Button>
  </Card >
}
export default connect(({ loading }) => ({
  loading: loading.effects['order/fakeEnterOrder'] || loading.effects['order/fakeReEnterOrder'],
}))(OrderForm);
